#-*- coding: utf-8 -*-
'''
settings.py 를 생성한다.
'''

import os
import tweepy

def get_settings_path():
    '''
    settings.py 파일의 경로를 반환한다

    @rtype: str
    '''
    return os.path.join(os.path.abspath(os.path.dirname(__file__)), 'settings.py')


def is_settings_exist():
    '''
    settings.py 파일이 존재하는지 검사한다

    @rtype: bool
    '''
    file_path = get_settings_path()
    return os.access(file_path, os.F_OK)


def check_oauth_info():
    '''
    settings.py 에 oauth_key, oauth_secret 이 모두 존재하는지 확인한다

    @rtype: bool
    '''
    import settings
    try:
        settings.OAUTH_KEY
        settings.OAUTH_SECRET
        return True
    except AttributeError:
        return False


def check_consumer_info():
    '''
    settings.py 에 consumer_key, consumer_secret 이 모두 존재하는지 확인한다

    @rtype: bool
    '''
    import settings
    try:
        settings.CONSUMER_KEY
        settings.CONSUMER_SECRET
        return True
    except AttributeError:
        return False


def get_oauth_info():
    '''
    OAuth Authorization 을 진행하고 OAuth Key, OAuth Secret 을 반환한다.

    @rtype: (str, str)
    '''
    import settings

    # 사용자에게 PIN Code 를 입력하는 URL 을 보여주고 PIN code 를 받는다
    auth = tweepy.OAuthHandler(
            settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
    url = auth.get_authorization_url()

    print "PIN Code URL:", url
    pin_code = raw_input("Enter PIN Code:")

    # PIN code 를 바탕으로 access token 을 확보한다
    try:
        auth.get_access_token(pin_code)
    except tweepy.TweepError:
        print "Error! Failed to get access token."
        raise

    print "Key   :", auth.access_token.key
    print "Secret:", auth.access_token.secret

    return auth.access_token.key, auth.access_token.secret


def append_to_file(values):
    '''
    settings.py 에 values 의 내용을 추가한다
    '''
    with open(get_settings_path(), 'a') as f:
        print >> f
        for key in values:
            print >> f, key, '=', repr(values[key])


def create_settings():
    '''
    settings.py 를 생성한다.
    '''
    with open(get_settings_path(), 'w') as f:
        print >> f, "#-*- coding: utf-8 -*-"


def get_consumer_info():
    '''
    사용자로부터 consumer_key, consumer_secret 을 입력받는다.

    @rtype: (str, str)
    '''

    consumer_key = raw_input("Enter Consumer Key:")
    consumer_secret = raw_input("Enter Consumer Secret:")

    return consumer_key.strip(), consumer_secret.strip()


def main():
    # 설정파일이 존재하는지 확인한다
    if not is_settings_exist():
        create_settings()

    if not check_oauth_info():
        if not check_consumer_info():
            consumer_key, consumer_secret = get_consumer_info()
            append_to_file({'CONSUMER_KEY': consumer_key, 'CONSUMER_SECRET': consumer_secret})

        oauth_key, oauth_secret = get_oauth_info()
        append_to_file({'OAUTH_KEY': oauth_key, 'OAUTH_SECRET': oauth_secret})

if __name__ == "__main__":
    main()
